package org.reborn.engine.util

import scala.collection.immutable.Map

/**
 * A simple implementation of a Registry.  
 *
 * Not thread-safe
 */
class SimpleRegistry[T] extends Registry[T]{
  private var nextRegistrationId:Int = 0
  private var registeredObjects:Map[Int,T] = Map()
 
  def register(obj:T):Int = {
    val id = getNextRegistrationId
    registeredObjects = registeredObjects +( (id,obj) )
    id
  }
  
  def unregister(id:Int):Unit = {
    val obj = registeredObjects.get(id)
    if(obj isDefined){
      registeredObjects -= (id)
    }
    else throw new RegistryException("Object is not registered.  Cannot unregister.")
  }
  
  def get(id:Int):Option[T] = {
    registeredObjects.get(id)
  }
  
  def reregister(id:Int,obj:T):Unit = {
    val existingObj = registeredObjects.get(id);
    if(existingObj isEmpty) throw new RegistryException("Object was not previously registered.  Cannot reregister.")
    
    registeredObjects += ((id,obj))
  }
 
  private def getNextRegistrationId():Int = {
	val curId = nextRegistrationId
	nextRegistrationId = nextRegistrationId + 1
    curId
  }
}
